import cgi
import os
import urllib
import logging

from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db
from app.models import assist, deposit, payment, household

_DEBUG = True

class BaseRequestHandler(webapp.RequestHandler):
  """Supplies a common template generation function.

  When you call generate(), we augment the template variables supplied with
  the current user in the 'user' variable and the current webapp request
  in the 'request' variable.
  """
  def generate(self, template_name, template_values={}):
    values = {
      'request': self.request,
      'user': users.GetCurrentUser(),
      'login_url': users.CreateLoginURL(self.request.uri),
      'logout_url': users.CreateLogoutURL(self.request.uri),
      'application_name': 'CMS',
    }
    values.update(template_values)
    directory = os.path.dirname(__file__)
    path = os.path.join(directory, os.path.join('templates', template_name))
    self.response.out.write(template.render(path, values, debug=_DEBUG))


class DepositList(BaseRequestHandler):
  def get(self):
    deposits = deposit.Deposit.all()
    self.generate('fixDepositList.html', {
        'deposits': deposits })

class FixPayment(BaseRequestHandler):
  def get(self, deposit):
    dep = db.get(db.Key(encoded=deposit))
    pays = payment.Payment.all().filter('deposit = ', dep)
    for pay in pays:
      pay.date = dep.date
      pay.year = str(dep.date.year)
      pay.put()
    self.generate('depositReport.html', {
        'payments': pays })

application = webapp.WSGIApplication([('/fix/payment/(.*)', FixPayment),
                                      ('/fix/payment.*', DepositList),
                                     ],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()  
